#include "ZeroMQPublisher.h"

#include <zmq.h>

ZeroMQPublisher::ZeroMQPublisher()
{
    m_zmqSocket  = nullptr;
    m_zmqContext = zmq_ctx_new();
}

ZeroMQPublisher::~ZeroMQPublisher()
{
    if (m_zmqSocket) {
        zmq_close(m_zmqSocket);
        m_zmqSocket = nullptr;
    }
    zmq_ctx_destroy(m_zmqContext);
}

bool ZeroMQPublisher::initialize(const char *address)
{
    m_zmqSocket = zmq_socket(m_zmqContext, ZMQ_PUB);
    if (zmq_bind(m_zmqSocket, address) != 0) {
        goto fail;
    }
    return true;

fail:
    zmq_close(m_zmqSocket);
    m_zmqSocket = nullptr;
    return false;
}

int ZeroMQPublisher::send(const char *buf, int len)
{
    if (!m_zmqSocket)
        return -1;

    return zmq_send(m_zmqSocket, buf, len, 0);
}
